#include "teacherui.h"
#include "ui_teacherui.h"

teacherui::teacherui(QSqlDatabase* db,QString account,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::teacherui)
{
    ui->setupUi(this);

    //初始化成员变量
    m_db = *db;
    m_account = account;

    this->setWindowTitle("欢迎使用学生信息管理系统!@教师"+account);

    ini();
}

teacherui::~teacherui()
{
    delete ui;
}

void teacherui::on_btnQuit_clicked()
{
    this->close();
}

void teacherui::ini()
{

    //初始化教师信息界面
    QSqlQuery query;
    query.exec("select * from tb_teacher where id='"+m_account+";'");

    query.first();
    if(query.isValid()){
        ui->labTeacher->setText(query.value("name").toString());
    }

    ui->editName->setText(query.value("name").toString());
    ui->labID->setText(query.value("id").toString());
    ui->combSex->setCurrentIndex(query.value("sex").toInt());
    ui->editPswd->setText(query.value("pswd").toString());
    ui->editPhone->setText(query.value("phone").toString());

    ui->editName->setReadOnly(true);
    ui->combSex->setEnabled(false);
    ui->editPswd->setReadOnly(true);
    ui->editPhone->setReadOnly(true);
    ui->btnReset->setEnabled(false);
    ui->btnSubmit->setEnabled(false);

    //实例化模型
    m_teachCourseModel = new QSqlTableModel(this);
    m_gradeModel = new QSqlTableModel(this);
    m_evaModel = new QSqlTableModel(this);

    //绑定数据表
    m_teachCourseModel->setTable("tb_teach");
    m_gradeModel->setTable("tb_grade");
    m_evaModel->setTable("tb_evaluate");

    //设置当主动提交修改时保存数据至数据库
    m_teachCourseModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    m_gradeModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    m_evaModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    //自动拉伸视图
    ui->tvCourse->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tvGrade->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tvEva->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    //设置数据表表头
    m_teachCourseModel->setHeaderData(0,Qt::Horizontal,"编号",Qt::DisplayRole);
    m_teachCourseModel->setHeaderData(1,Qt::Horizontal,"教师编号",Qt::DisplayRole);
    m_teachCourseModel->setHeaderData(2,Qt::Horizontal,"教师名字",Qt::DisplayRole);
    m_teachCourseModel->setHeaderData(3,Qt::Horizontal,"课程编号",Qt::DisplayRole);
    m_teachCourseModel->setHeaderData(4,Qt::Horizontal,"课程名称",Qt::DisplayRole);
    m_teachCourseModel->setHeaderData(5,Qt::Horizontal,"课程类型",Qt::DisplayRole);

    m_gradeModel->setHeaderData(0,Qt::Horizontal,"编号",Qt::DisplayRole);
    m_gradeModel->setHeaderData(1,Qt::Horizontal,"学生编号",Qt::DisplayRole);
    m_gradeModel->setHeaderData(2,Qt::Horizontal,"学生名字",Qt::DisplayRole);
    m_gradeModel->setHeaderData(3,Qt::Horizontal,"课程编号",Qt::DisplayRole);
    m_gradeModel->setHeaderData(4,Qt::Horizontal,"课程名称",Qt::DisplayRole);
    m_gradeModel->setHeaderData(5,Qt::Horizontal,"课程类型",Qt::DisplayRole);
    m_gradeModel->setHeaderData(6,Qt::Horizontal,"得分",Qt::DisplayRole);
    m_gradeModel->setHeaderData(7,Qt::Horizontal,"教师编号",Qt::DisplayRole);
    m_gradeModel->setHeaderData(8,Qt::Horizontal,"教师姓名",Qt::DisplayRole);

    m_evaModel->setHeaderData(0,Qt::Horizontal,"编号",Qt::DisplayRole);
    m_evaModel->setHeaderData(1,Qt::Horizontal,"学生编号",Qt::DisplayRole);
    m_evaModel->setHeaderData(2,Qt::Horizontal,"学生名字",Qt::DisplayRole);
    m_evaModel->setHeaderData(3,Qt::Horizontal,"老师编号",Qt::DisplayRole);
    m_evaModel->setHeaderData(4,Qt::Horizontal,"老师名字",Qt::DisplayRole);
    m_evaModel->setHeaderData(5,Qt::Horizontal,"评语",Qt::DisplayRole);
    m_evaModel->setHeaderData(6,Qt::Horizontal,"评分",Qt::DisplayRole);

    //获取表格数
    m_teachCourseModel->select();
    m_gradeModel->select();
    m_evaModel->select();



    //绑定视图和模型
    ui->tvCourse->setModel(m_teachCourseModel);
    ui->tvGrade->setModel(m_gradeModel);
    ui->tvEva->setModel(m_evaModel);

    //筛选数据

    //默认按照成绩降序排序
    ui->tvGrade->sortByColumn(6,Qt::DescendingOrder);


    for(int i = 0;i < m_teachCourseModel->rowCount(); ++i){
        if(m_teachCourseModel->data(m_teachCourseModel->index(i,1)).toString() != m_account){
            ui->tvCourse->hideRow(i);
        }
    }

    for(int i = 0;i < m_gradeModel->rowCount(); ++i){
        if(m_gradeModel->data(m_gradeModel->index(i,7)).toString() != m_account){
            ui->tvGrade->hideRow(i);
        }
    }

    for(int i = 0;i < m_evaModel->rowCount(); ++i){
        if(m_evaModel->data(m_evaModel->index(i,3)).toString() != m_account){
            ui->tvEva->hideRow(i);
        }
    }



    //初始化课程comb
    for(int i = 0;i < m_gradeModel->rowCount(); ++i){
        if(ui->tvGrade->isRowHidden(i)){
            continue;
        }
        bool contain = false;
        for(int j = 0;j < ui->combCourse->count(); ++j){
            if(ui->combCourse->itemText(j) == m_gradeModel->data(m_gradeModel->index(i,4)).toString()){
                contain = true;
                break;
            }
        }
        if(!contain){
            ui->combCourse->addItem(m_gradeModel->data(m_gradeModel->index(i,4)).toString());
        }
    }

    //初始化班级comb
    for(int i = 0; i < m_gradeModel->rowCount();++i){
        bool ok = false;
        QSqlQuery query;
        query.exec("select * from tb_student where id="+m_gradeModel->data(m_gradeModel->index(i,1)).toString()+";");
        if(query.size() == 0){
            QMessageBox::warning(0,"警告","学生信息查找失败!");
            break;
        }
        query.first();
        QString stuClass = query.value("class").toString();
        for(int j = 1;j < ui->combClass->count(); ++j){
            if(ui->combClass->itemText(j) == stuClass){
                ok = true;
                break;
            }
        }
        if(ok == false){
            ui->combClass->addItem(stuClass);
        }
    }

    //统计数据
    int totalCount = 0;
    int passCount = 0;
    double totalScore = 0;
    QList<double> theList;
    for(int i = 0;i < m_gradeModel->rowCount(); ++i){
        if(ui->tvGrade->isRowHidden(i)){
            continue;
        }

        double score = m_gradeModel->data(m_gradeModel->index(i,6)).toDouble();
        totalScore += score;
        ++totalCount;
        if(score >= 60.0){
            ++passCount;
        }
        theList.append(score);
    }

    if(totalCount == 0){
        ui->labAverage->setText(QString::asprintf("0"));
        ui->labStaDev->setText(QString::asprintf("0"));
        ui->labPassRate->setText(QString::asprintf("0"));
        return;
    }

    double average;
    double staDev;
    double passRate;

    average = totalScore / totalCount;
    double atotal = 0;
    for(int i = 0;i < theList.count();++i){
        atotal += abs(average-theList.at(i)) * abs(average-theList.at(i));
    }
    staDev = sqrt(atotal/totalCount);
    passRate = (double)passCount / (double)totalCount;

    ui->labAverage->setText(QString::asprintf("%.2f",average));
    ui->labStaDev->setText(QString::asprintf("%.2f",staDev));
    ui->labPassRate->setText(QString::asprintf("%.2f%%",passRate*100));
}


void teacherui::on_cheEdit_stateChanged(int arg1)
{
    ui->editName->setReadOnly(!arg1);
    ui->combSex->setEnabled(arg1);
    ui->editPswd->setReadOnly(!arg1);
    ui->editPhone->setReadOnly(!arg1);
    ui->btnReset->setEnabled(arg1);
    ui->btnSubmit->setEnabled(arg1);
}


void teacherui::on_btnReset_clicked()
{
    QSqlQuery query;
    query.exec("select * from tb_teacher where id='"+m_account+";'");

    query.first();
    if(query.isValid()){
        ui->labTeacher->setText(query.value("name").toString());
    }

    ui->editName->setText(query.value("name").toString());
    ui->labID->setText(query.value("id").toString());
    ui->combSex->setCurrentIndex(query.value("sex").toInt());
    ui->editPswd->setText(query.value("pswd").toString());
    ui->editPhone->setText(query.value("phone").toString());

    ui->editName->setReadOnly(true);
    ui->combSex->setEnabled(false);
    ui->editPswd->setReadOnly(true);
    ui->editPhone->setReadOnly(true);
    ui->btnReset->setEnabled(false);
    ui->btnSubmit->setEnabled(false);

    ui->cheEdit->setChecked(false);
}


void teacherui::on_btnSubmit_clicked()
{
    QSqlQuery query;
    if(query.exec("update tb_teacher set pswd='"+ui->editPswd->text()+"',name='"+ui->editName->text()
                  +"',sex="+QString::asprintf("%d",ui->combSex->currentIndex())+",phone='"
                  +ui->editPhone->text()+"' where id="+ui->labID->text()+";")){
        QMessageBox::information(0,"提示","提交成功!");
        ui->btnReset->click();
    }
}


void teacherui::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
    if(item->text(column) == "教师信息管理"){
        ui->btnReset->click();
        ui->stackedWidget->setCurrentWidget(ui->pagTeacher);
    }else if(item->text(column) == "我的课表"){

        ui->stackedWidget->setCurrentWidget(ui->pagCourse);
    }else if(item->text(column) == "成绩管理"){

        ui->stackedWidget->setCurrentWidget(ui->pagGrade);
    }else if(item->text(column) == "评教结果"){

        ui->stackedWidget->setCurrentWidget(ui->pagEva);
    }
}


void teacherui::on_btnAppendTeacher_clicked()
{
    m_gradeModel->insertRow(m_gradeModel->rowCount());
}


void teacherui::on_btnDeleteTeacher_clicked()
{
    if(ui->tvGrade->currentIndex().isValid()){
        m_gradeModel->removeRow(ui->tvGrade->currentIndex().row());
    }
}


void teacherui::on_btnResetTeacher_clicked()
{
    m_gradeModel->select();
}


void teacherui::on_btnSubmitTeacher_clicked()
{
    if(m_gradeModel->isDirty()){
        if(m_gradeModel->submitAll()){
            QMessageBox::information(0,"提示","提交成功!");
        }
    }
}


void teacherui::on_btnScreen_clicked()
{
    //显示所有行
    for(int i = 0;i < m_gradeModel->rowCount(); ++i){
        ui->tvGrade->showRow(i);
    }



    //排序
    if(ui->btnAsc->isChecked()){
        ui->tvGrade->sortByColumn(6,Qt::AscendingOrder);
    }else{
        ui->tvGrade->sortByColumn(6,Qt::DescendingOrder);
    }

    //筛选该老师的成绩单
    for(int i = 0;i < m_gradeModel->rowCount(); ++i){
        if(m_gradeModel->data(m_gradeModel->index(i,7)).toString() != m_account){
            ui->tvGrade->hideRow(i);
        }
    }

    //筛选行
    //通过课程名称筛选
    if(ui->combCourse->currentText() != "所有课程"){
        for(int i = 0;i < m_gradeModel->rowCount(); ++i){
            if(ui->tvGrade->isRowHidden(i)){
                continue;
            }else{
                if(m_gradeModel->data(m_gradeModel->index(i,4)).toString() != ui->combCourse->currentText()){
                    ui->tvGrade->hideRow(i);
                }
            }
        }
    }

    //通过分数区间筛选
    if((ui->spinScoreMin->value() != 0 || ui->spinScoreMax->value() != 0) && (ui->spinScoreMin->value() <= ui->spinScoreMax->value())){
        for(int i = 0;i < m_gradeModel->rowCount(); ++i){
            if(ui->tvGrade->isRowHidden(i)){
                continue;
            }else{
                if(!(m_gradeModel->data(m_gradeModel->index(i,6)).toDouble() >= ui->spinScoreMin->value() && m_gradeModel->data(m_gradeModel->index(i,6)).toDouble() <= ui->spinScoreMax->value())){
                    ui->tvGrade->hideRow(i);
                }
            }
        }
    }

    //通过班级筛选
    QSqlQuery query;
    if(ui->combClass->currentText() != "所有班级"){
        for(int i = 0; i < m_gradeModel->rowCount(); ++i){
            if(ui->tvGrade->isRowHidden(i)){
                continue;
            }else{
                query.exec("select * from tb_student where id="+m_gradeModel->data(m_gradeModel->index(i,1)).toString()+";");
                query.first();
                if(ui->combClass->currentText() != query.value("class")){
                    ui->tvGrade->hideRow(i);
                }
            }
        }
    }



    //统计数据
    int totalCount = 0;
    int passCount = 0;
    double totalScore = 0;
    QList<double> theList;
    for(int i = 0;i < m_gradeModel->rowCount(); ++i){
        if(ui->tvGrade->isRowHidden(i)){
            continue;
        }

        double score = m_gradeModel->data(m_gradeModel->index(i,6)).toDouble();
        totalScore += score;
        ++totalCount;
        if(score >= 60.0){
            ++passCount;
        }
        theList.append(score);
    }

    if(totalCount == 0){
        ui->labAverage->setText(QString::asprintf("0"));
        ui->labStaDev->setText(QString::asprintf("0"));
        ui->labPassRate->setText(QString::asprintf("0"));
        return;
    }

    double average;
    double staDev;
    double passRate;

    average = totalScore / totalCount;
    double atotal = 0;
    for(int i = 0;i < theList.count();++i){
        atotal += abs(average-theList.at(i)) * abs(average-theList.at(i));
    }
    staDev = sqrt(atotal/totalCount);
    passRate = (double)passCount / (double)totalCount;

    ui->labAverage->setText(QString::asprintf("%.2f",average));
    ui->labStaDev->setText(QString::asprintf("%.2f",staDev));
    ui->labPassRate->setText(QString::asprintf("%.2f%%",passRate*100));
}


void teacherui::on_btnFind_clicked()
{
    if(!ui->editFind->text().isEmpty()){
        for(int i = 0; i < m_gradeModel->rowCount(); ++i){
            for(int j = 0; j < m_gradeModel->columnCount(); ++j){
                if(!ui->tvGrade->isRowHidden(i) && m_gradeModel->data(m_gradeModel->index(i,j)).toString().contains(ui->editFind->text())){
                    ui->tvGrade->selectRow(i);
                }
            }
        }
    }
}

